package com.redpixy.monit.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redpixy.monit.common.Address;
import com.redpixy.monit.common.param.MailParam;
import com.redpixy.monit.common.util.DateUtil;
import com.redpixy.monit.mail.MailSender;
import com.redpixy.monit.ping.HttpCheck;

public class MonitSchedule implements Runnable {
	private static final Logger log = LoggerFactory
			.getLogger(MonitSchedule.class);

	@Override
	public void run() {
		try {
			log.info("----->开始检测服务。。。。");
			checkIsRunning();
			log.info("----->检测服务完成。。。。");
		} catch (Exception e) {
			log.error("运行出现异常", e);
		}

	}

	/**
	 * 检查设定的地址是否运行正常
	 */
	private void checkIsRunning() {
		for (Address add : MailParam.CHECK_ADRESS) {
			try {
			String to[] = MailParam.RECEIVE;
			String url = add.getFullURL();
			boolean running = add.getAddressType()==1?HttpCheck.checkUrl(add.getUrl()) : HttpCheck.checkIP(add.getIp(),add.getPort());
			if (!running) {
				if (!MailParam.ERRORADDRESS.containsKey(url)) {
				    MailParam.ERRORADDRESS.put(url, add);
			     }
				add.setErrorCount(add.getErrorCount() +1);
				if (add.getErrorCount() <= 1) {
					String title = add.getName() + "运行异常";
					String context = add.getName() + "【运行异常】，"+ url +"   无法连接"
							+ "<br><br><br>"+DateUtil.getDateTime()+"<br><br><br><br><br><br>";
					MailSender.sendMail(title, context, to);
					log.warn("----->【运行异常】-{},地址:{},发送通知邮件",add.getName(),url);
				}else if(add.getErrorCount() > 1){
					log.warn("----->【运行异常】-{},地址:{},已发送通知邮件",add.getName(),url);
				}

			} else {
				if (MailParam.ERRORADDRESS.containsKey(url)) {
				    MailParam.ERRORADDRESS.remove(url);
			     }
				log.debug("----->[运行正常]-{},地址:{}",add.getName(),url);
			}
			} catch (Exception e) {
				log.error("", e);
			}
		}
			
	}

}
